import React, { Component } from 'react'
import '../assets/style/formInput_c.less'
import axios from '../utils/request';

export default class FormInput extends Component {
    static defaultProps = {
        placeholder: "",
        type: "text" 
    }
    constructor(props){
        super(props)
        this.state = {
            countdown: "验证码",
            Time: ""
        }
        this.handleClick2 = this.handleClick2.bind(this)
    }
    setTime(obj){
        if(this.state.countdown == "验证码"){
            obj.setAttribute("disabled",true)
            this.setState({
                countdown: 3
            })
        }else{
            if(this.state.countdown == 0){
                this.setState({
                    countdown: "验证码"
                })
                obj.removeAttribute("disabled")
                return 
            }
            this.setState({
                countdown: this.state.countdown*1-1
            })
        }
        this.state.Time = setTimeout(()=>{
          this.setTime(obj)
        },1000)
    }
    componentWillUnmount(){
        clearTimeout(this.state.Time)
    }
    async handleClick2(e){
        if(!(/^1[34578]\d{9}$/.test(this.props.username))){
            alert("手机号码有误，请重填");
        }else{
            this.setTime(e.target)
            let phone = {phone: this.props.username}
            const res = await axios({
                method: 'post',
                url: "/checkCode",
                data: phone
            })
            console.log(res);
        }
    }
    render() {
        return (
            this.props.types === "code"?
            <div className="input-group">
                <input value={this.props.value}  onChange={this.props.onChange} type={this.props.type} placeholder={this.props.placeholder} />
                <i><input style={{fontSize: "10px"}} type="button" value={this.state.countdown} onClick={this.handleClick2}/></i>
            </div>:
            <div className="input-group">
                <i><img src={require("../assets/images/"+this.props.src)} alt=""/></i>
                <input value={this.props.value}  onChange={this.props.onChange} type={this.props.type} placeholder={this.props.placeholder} />
            </div>
        )
    }
}
